<template>
  <div class="main" v-loading="loading">
    <div :id="mapId" class="main-map"></div>
  </div>
</template>
<script lang="ts" setup>
import {getCurrentInstance, onMounted, ref, watch} from 'vue';
import axios from 'axios';
import {FmMapManager, PathConfig} from '@/views/monitor/fmmapmanager';
import {imgPathConfig} from '@/views/monitor/monitorConfig';
import {wgs84togcj02} from '@/views/monitor/fmmapmanager/Tools/transfrom';

const $http = getCurrentInstance()?.appContext.config.globalProperties.$http;

const props = defineProps({
  mapId: {
    type: String,
    default: '',
  },
  missionId: {
    type: String,
    default: '',
  },
});

watch(
  () => props.mapId,
  () => {
    initMap(props.mapId);
  },
);

const loading = ref(false);
let map;
const isWgs = 'gcj02';
const feimaManager = ref(null);
let flyingAirline = ''; // 飞马无人机轨迹
let routeLine = ''; // 飞马航线
let feimaPlaneMarker = ''; // 飞马无人机图标标记点
let flyArea = []; // 阴影区域

const missionId = ref('');
const emits = defineEmits(['getFlight']);

// 获取监控详情数据
const getMonitorDetail = async () => {
  const exportUrl = `${import.meta.env.VITE_MONITOR_URL}/flightMission/monitor`;
  const data = await axios({
    method: 'get',
    url: exportUrl,
    headers: {
      token: localStorage.getItem('token'),
    },
    params: {
      local_id: missionId.value,
    },
  });
  init(data.data.data);
};

// 初始化地图
const initMap = (mapId) => {
  map = new AMap.Map(mapId, {
    resizeEnable: true,
    viewMode: '2D',
    zoom: 4,
    features: ['bg', 'road', 'building', 'point'],
  });
};

// 设置起飞点和结束点标记点
const newMarker = (makerData, name) => {
  name = new AMap.Marker({
    position: makerData.lnglat,
    icon: makerData.icon,
    zIndex: 111,
    offset: new AMap.Pixel(0, 0),
    anchor: 'center',
  });
  map.add(name);
};
// 设置飞马无人机图标标记点，因为要多次赋值经纬度，所以要绑定数据
const setFeimaPlaneMarker = (data) => {
  feimaPlaneMarker = new AMap.Marker({
    position: data.lnglat,
    icon: data.icon,
    zIndex: 111,
    offset: new AMap.Pixel(0, 0),
    anchor: 'center',
  });
  map.add(feimaPlaneMarker);
};
// 获取websocket Url
const getPlaneWebsocketUrl = () =>
  new Promise((resolve, reject) => {
    $http
      .get('//airport.afuav.com/api/device/monitor/info', {
        serial_no: props.mapId,
      })
      .then((response) => {
        resolve(response.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
// 获取阴影区域数据
const getFlyArea = (areaData) => {
  const areaArr = [];
  let posi = [];
  areaData.survey_area_coordinate_points.split(';').forEach((item) => {
    if (item) {
      const [lat, lng] = item.split(',');
      posi = wgs84togcj02(lng, lat);
      areaArr.push([posi.longitude, posi.latitude]);
    }
  });
  return areaArr;
};
// 初始化飞行数据
const init = async (data) => {
  loading.value = true;
  let wsUrl = '';
  let tbId = '';
  await getPlaneWebsocketUrl().then((res) => {
    wsUrl = res.ws_url;
    tbId = res.data.tb_id;
  });

  const fmMonitorOptions = {
    flight_data: data.data, // 必填。 请求到的任务数据
    local_id: data.data.local_id, // 必填。任务id
    url: wsUrl, // 必填。websocket监听地址
    platform: '', // 选填。不填默认web端
    isWgsNeeded: false, // 选填。不填默认false， 即 不生成wgs航线/标记点
    /*
     * airlineOptions 航线配置
     * base_airline_options: 底层航线，upper_airline_options： 上层航线
     * 具体航线配置参考Polyline文档
     */
    airlineOptions: {
      base_airline_options: {
        // 选填。底层航线
        strokeColor: '#e8a443',
        strokeWidth: 2,
        id: '1',
      },
      upper_airline_options: {
        // 选填。上层航线
        strokeColor: '#1686cc',
        strokeWidth: 2,
        id: '2',
      },
    },
    /*
     * markersOptions 标记点配置
     * landingMarker: 起飞点，endPointMarker: 终止点，planeMarker:飞机；
     * 网页端参考amap marker文档, uniapp端参考文档。配置除图片和位置外的所需参数
     */
    markersOptions: {
      landingMarker: {}, // 起飞点
      endPointMarker: {}, // 终止点
      planeMarker: {}, // 飞机
    },
  };

  fmMonitorOptions.wsMessageFunc = () =>
    `{"attrSubCmds":[],"tsSubCmds":[{"entityType":"DEVICE","entityId":"${tbId}","scope":"LATEST_TELEMETRY","cmdId":1}],"historyCmds":[]}`;

  PathConfig.setConfigs(imgPathConfig); // 图片路径
  feimaManager.value = new FmMapManager(fmMonitorOptions);
  feimaManager.value.createMonitor();
  feimaManager.value.onPlaneMove = (item) => {
    getFeimaWebsocketData(item);
  };
  handleClick(feimaManager.value);
  if (isWgs.value === 'wgs84') {
    routeLine = new AMap.Polyline({
      ...feimaManager.value.wgs84Airline,
      zIndex: 50,
    });
    flyArea = new AMap.Polygon({
      path: getFlyArea(data.data),
      fillColor: '#fdfbb1', // 多边形填充颜色
      borderWeight: 2, // 线条宽度，默认为 1
      strokeColor: '#e8a443', // 线条颜色
      zIndex: 30,
    });
    map.add(flyArea);
    routeLine.setMap(map);
    map.setFitView(routeLine);
    newMarker(feimaManager.value.wgs84Markers[0], 'homePoint');
    newMarker(feimaManager.value.wgs84Markers[1], 'endPoint');
  } else {
    routeLine = new AMap.Polyline({
      ...feimaManager.value.airline,
      zIndex: 50,
    });

    flyArea = new AMap.Polygon({
      path: getFlyArea(data.data),
      fillColor: '#fdfbb1', // 多边形填充颜色
      borderWeight: 2, // 线条宽度，默认为 1
      strokeColor: '#e8a443', // 线条颜色
      zIndex: 30,
    });

    map.add(flyArea);
    routeLine.setMap(map);
    map.setFitView(routeLine);
    newMarker(feimaManager.value.markers[0], 'homePoint');
    newMarker(feimaManager.value.markers[1], 'endPoint');
  }
  // 设置飞机
  // websocket端口
  feimaManager.value.errorMonitor = (error) => {
    this.$message('连接已断开，请重新进入');
  };
  loading.value = false;
};
// 向父级传飞行数据信息
const handleClick = (item) => {
  emits('getFlight', item);
};
// 飞马标记点移动时的数据
const getFeimaWebsocketData = (data) => {
  if (flyingAirline === '') {
    flyingAirline = new AMap.Polyline({
      path: [],
      strokeColor: feimaManager.value.wgs84FlyingAirline.strokeColor,
      strokeWeight: feimaManager.value.wgs84FlyingAirline.strokeWidth,
      zIndex: 50,
    });
    flyingAirline.setMap(map);
  } else {
    const path = flyingAirline.getPath();
    if (isWgs.value === 'wgs84') {
      path.push([
        feimaManager.value.fmMonitor.wgs84CurrentPosition.longitude,
        feimaManager.value.fmMonitor.wgs84CurrentPosition.latitude,
      ]);
      flyingAirline.setPath(path);
    } else {
      path.push([
        feimaManager.value.fmMonitor.currentPosition.longitude,
        feimaManager.value.fmMonitor.currentPosition.latitude,
      ]);
      flyingAirline.setPath(path);
    }
  }
  if (feimaPlaneMarker === '') {
    if (feimaManager.value.markers[2] !== undefined) {
      const planeMarker = feimaManager.value.markers[2];
      setFeimaPlaneMarker(planeMarker);
    }
  } else {
    if (isWgs.value === 'wgs84') {
      feimaPlaneMarker.setPosition([
        feimaManager.value.fmMonitor.wgs84CurrentPosition.longitude,
        feimaManager.value.fmMonitor.wgs84CurrentPosition.latitude,
      ]);
    } else {
      feimaPlaneMarker.setPosition([
        feimaManager.value.fmMonitor.currentPosition.longitude,
        feimaManager.value.fmMonitor.currentPosition.latitude,
      ]);
    }
    feimaPlaneMarker && feimaPlaneMarker.setAngle(feimaManager.value.fmMonitor.planeRotate);
  }
};

onMounted(() => {
  setTimeout(() => {
    initMap(props.mapId);
    missionId.value = props.missionId;
    getMonitorDetail();
  }, 10);
});
</script>
<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;

  &-map {
    height: 100%;
  }
}
</style>
